from django_redis import get_redis_connection
from rest_framework import serializers


class RegisterSmsCodeSerializer(serializers.Serializer):

    text = serializers.CharField(required=True,max_length=4,min_length=4,label ="输入验证码")
    # image_code_id = serializers.CharField(required=True,label="uuid")
    image_code_id = serializers.UUIDField(required=True, label="uuid")

    def validate(self, attrs):

        text = attrs.get("text")
        image_code_id = attrs.get("image_code_id")

        redis_conn = get_redis_connection("code")
        redis_text = redis_conn.get("img_%s" %image_code_id)

        if redis_text is None:
            raise serializers.ValidationError("图片验证码过期")

        if redis_text.decode().lower() != text.lower():
            raise serializers.ValidationError('输入不一致')

        return attrs
